package br.ufc.DAO.Implements;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.ufc.DAO.IDisciplina;
import br.ufc.si.model.Disciplina;
import br.ufc.util.HibernateUtil;

public class DisciplinaDAO implements IDisciplina {

	public void save(Disciplina dis) {
		Session sessao = HibernateUtil.getSession();

		Transaction txt = sessao.beginTransaction();

		try {
			sessao.save(dis);
			txt.commit();
		} catch (Exception e) {
			txt.rollback();
		} finally {
			sessao.close();
		}

	}

	public void update(Disciplina dis) {
		Session sessao = HibernateUtil.getSession();
		Transaction trasaction = sessao.beginTransaction();
		try {
			sessao.update(dis);
			trasaction.commit();

		} catch (Exception e) {
			trasaction.rollback();
		} finally {
			sessao.close();
		}

	}

	public void delete(Disciplina dis) {
		Session sessao = HibernateUtil.getSession();
		Transaction txt = sessao.beginTransaction();

		try {
			sessao.delete(dis);
			txt.commit();

		} catch (Exception e) {
			txt.rollback();
		} finally {
			sessao.close();
		}

	}

	public List<Disciplina> ListAll() {
		Session session = HibernateUtil.getSession();
		try {
			Criteria criteria = session.createCriteria(Disciplina.class);
			return (List<Disciplina>) criteria.list();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	public Disciplina listDisciplinaByCodigo(int codigo) {
		Session session = HibernateUtil.getSession();
		String query = "from Disciplina where codigo = :codigo";
		try {
			return (Disciplina) session.createQuery(query)
					.setInteger("codigo", codigo).uniqueResult();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

	public List<Disciplina> listAllDisciplinasByCodigo(int codigo) {
		Session session = HibernateUtil.getSession();
		String query = "from Disciplina where codigo_curso = :codigo";
		try {
			return session.createQuery(query).setInteger("codigo", codigo)
					.list();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

}
